package com.xlhj.boot.util;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author: liucaijing
 * @description: CSVUtils
 * @date: 2021/6/15 14:59
 */
public class CSVUtils {

    private final static String LINE_SEPARATOR = "\n";
    private final static String PATH = "";

    /**
     * 将数据写入CSV文件
     * @param fileName
     * @param dataList
     * @return
     */
    public static File makeFileForCSV(String fileName, List<Map<String, Object>> dataList) {
        File file = null;
        try {
            file = File.createTempFile(fileName, ".csv", new File(PATH));
            CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator(LINE_SEPARATOR);
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, format);
            //解析表头信息
            Map<String, Object> headMap = dataList.get(0);
            Set<String> headStr = headMap.keySet();
            //将表头信息写入CSV文件
            csvPrinter.printRecord(headStr);
            //解析数据
            //将数据信息写入CSV文件
            csvPrinter.printRecord();
            csvPrinter.close();
            bufferedWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }
}
